<?php

namespace app\agent\controller;

use app\admin\model\Config;
use app\attachment\controller\ApiUpload as Upload;
use app\common\controller\Adminbase;
use app\model\AdminAgent;
use app\model\DistributionSetting;
use app\model\User as UserModel;
use app\service\AgentService;
use think\Db;
use util\Logger;
use Wechat\MiniApp;

class User extends Adminbase
{
    public function index()
    {
        $model = 'User';

        $agent = AgentService::getAgentInfo(UID);
        if ($this->request->isAjax()) {
            $map      = $this->buildParamsMap();
            $page     = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : 20;

            $query       = UserModel::where($map)
                ->where('bind_status', 1)
                ->where('agent_id', $agent['id']);
            $count_query = clone $query;

            $list  = $query
                ->field('*')
                ->withAttr('parent_user_id', function ($value) {
                    return $value == 0 ? '直属合作商' : $value;
                })
                ->page($page, $pageSize)
                ->order('id', 'desc')
                ->select();
            $total = $count_query->count();

            if ($list) {
                $info  = DistributionSetting::field('id, type, value')->where('uuid', 'setting')->find();
                $value = json_decode($info['value'], true);
                foreach ($list as &$item) {
                    $level_info    = $item['level'] == 2 ? $value[1] : $value[0];
                    $item['level'] = $level_info['name'];
                }
            }

            $result = ["code" => 0, "count" => $total, "data" => $list];
            return json($result);
        }

        //生成列表数据
        $builder = new \app\common\controller\ListBuilder();
        if (in_array(AdminAgent::RULE_INVITE_USER, $agent['rules'])) {
            $builder->setLayerBtn([
                ['title' => '邀请推客', 'url' => url('invite', ['agent_id' => $agent['id']]), 'area' => "['60vw', '80vh']"]
            ]);
        }

        $builder
            ->setDelBtn(false)
            ->setAddBtn(false)
            ->setDelAllBtn(false)
            ->setDataUrl()
            ->setFormUrl('')
            ->setLimit()
            ->setModel($model)
            ->addTableCheckBox()
            ->setSwitchTpl('switchTpl', 'status')
            ->addTableColumn('id', '推客ID', null, null, true)
            ->addTableColumn('parent_user_id', '上级用户id')
            ->addTableColumn('nickname', '昵称')
            ->addTableColumn('mobile', '手机号')
            ->addTableColumn('level', '等级')
            ->addTableColumn('create_time', '创建时间')
            ->addTableOperation()
            ->setListLayerBtn([
                ['title' => '编辑', 'url' => url('form'), 'area' => "['50vw', '60vh']"]
            ])
            ->returnForm();

        $this->assign('module', 'app');
        return $this->fetch('admin@common/lists');
    }

    public function form()
    {
        $model = 'User';

        $id   = $this->request->param('id/d');
        $info = \app\model\User::get($id);
        $this->assign('id', $id);
        $this->assign('action', 2);
        if ($this->request->isPost()) {
            $data        = $this->request->post();
            $level_count = AdminAgent::where('id', $info['agent_id'])->value('level_count');
            if ($level_count <= 0) {
                return json(['code' => 1, 'msg' => '升级次数不足']);
            }
            \app\model\User::update([
                'level' => $data['level'],
            ], ['id' => $id]);
            if ($data['level'] > $info['level']) {
                AdminAgent::where('id', $info['agent_id'])->setDec('level_count');
            }
            return json(['code' => 0, 'msg' => '操作成功', 'data' => ['close' => 1]]);
        }

        $setting = DistributionSetting::field('id, type, value')->where('uuid', 'setting')->find();
        $value   = json_decode($setting['value'], true);
        $level   = [];
        foreach ($value as $key => $val) {
            $level[$key + 1] = $val['name'];
        }

        $builder = new \app\common\controller\FormBuilder();
        $builder
            ->setModel($model)
            ->setUrl('form')
            ->setSuccessUrl()
            ->addFormItem('level', 'radio', '推客等级', '', $level)
            ->setFormData($info)
            ->returnForm();
        $this->assign('module', 'app');
        $this->assign('is_verify', 0);
        return $this->fetch('admin@common/form');
    }

    public function invite()
    {
        $agent_id = $this->request->param('agent_id/d');
        $qrcode   = AdminAgent::where('id', $agent_id)->value('qrcode');
        if (!empty($qrcode)) {
            $this->assign('qrcode', $qrcode);
            return $this->fetch('agent/invite');
        }
        try {
            // 把二维码上传到云存储
            $upload_path = config('upload_path');
            $filepath    = 'qrcode';
            $qrcodePath  = $upload_path . '/' . $filepath . '/';
            if (!file_exists($qrcodePath)) {
                mkdir($qrcodePath, 0755, true);
            }
            $filename = "agent-{$agent_id}.png";
            $filePath = $qrcodePath . $filename;

            $imageData = MiniApp::getInstance()->createQRCode('pages/index/index', "code=$agent_id");
            if (empty($imageData)) {
                $this->error('获取二维码失败', url('agent/user/index'));
            }
            // 保存文件
            if (!file_put_contents($filePath, $imageData)) {
                $this->error('生成二维码失败', url('agent/user/index'));
            }
            //获取上传驱动
            $driver = Config::where('name', 'upload_driver')->value('value');
            $file   = $qrcodePath . '/' . $filename;
            if ($driver != 'local') {
                //把图片上传到第三方存储
                $upload   = new Upload();
                $oss_file = $upload->upload_local_file($filename, $filepath, $file); //值为空本地文件
                //删除本地文件
                if ($oss_file) {
                    @unlink($file);
                }
                AdminAgent::where('id', $agent_id)->update(['qrcode' => $oss_file]);
            } else {
                $oss_file = request()->domain() . '/uploads/' . $filepath . '/' . $filename;
            }
            AdminAgent::where('id', $agent_id)->update(['qrcode' => $oss_file]);
            $this->assign('qrcode', $oss_file);
            return $this->fetch('agent/invite');
        } catch (\Exception $e) {
            $log = [
                'error' => $e->getMessage(),
                'file'  => $e->getFile(),
                'line'  => $e->getLine(),
            ];
            Logger::error('代码异常', $log);
            $this->error('获取二维码失败', url('agent/user/index'));
        }
    }

}
